package com.xq.spring.beans;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 重点关注:此Bean实现了ApplicationContextAware接口,由此可以获取Spring容器的引用.
 * 相似的接口还有BeanFactoryAware,BeanNameAware,ResourceLoaderAware
 * 
 * @author 郭凯强
 */
public class Chinese implements Person, ApplicationContextAware,BeanFactoryAware,
		InitializingBean {
	private Marker marker = MarkerFactory.getMarker("debug");
	private final Logger logger = LoggerFactory.getLogger(Chinese.class);

	private Axe axe;
	private String name;
	private ApplicationContext applicationContext;
	private BeanFactory beanFactory;

	public Chinese() {
		logger.debug(marker, "实例化Bean={}", Chinese.class.getName());
	}

	@Override
	public void useAxe() {
		logger.debug(marker, "{}使用斧头!", Chinese.class.getSimpleName());
		if (applicationContext!=null) {
			logger.debug(marker, "获取Spring容器的id={}", applicationContext.getId());
		}
		if (beanFactory!=null) {
			logger.debug(marker, "获取Spring容器的Class={}", beanFactory.getClass());
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		logger.debug(marker, "让Bean获取Spring容器={}", applicationContext);
	}

	public Axe getAxe() {
		return axe;
	}

	public void setAxe(Axe axe) {
		this.axe = axe;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/**
	 * 可以使用Bean的生命周期方法替代实现InitializingBean接口.此处仅作测试使用.
	 * 
	 * @throws Exception
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		logger.debug(marker, "执行初始化方法{}", "afterPropertiesSet");
	}

	/**
	 * 可替代实现InitializingBean接口,执行初始化功能
	 */
	public void init() {
		logger.debug(marker, "执行初始化方法{}", "init");
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory=beanFactory;
		logger.debug(marker, "让Bean获取Spring容器={}", beanFactory);
	}
}
